﻿using System.Collections;
using System.Collections.Generic;
using System.Data;
using Newtonsoft.Json;

namespace Dan.Common
{
    public class JsonHelper
    {

        public static Result Success(object data = null, int count = 0, string msg = "")
        {
            Result result = new Result
            {
                isok = true,
                data = data,
                msg = msg,
                count = count
            };
            return result;
        }

        public static Result Error(string msg = "操作失败")
        {
            Result result = new Result
            {
                isok = false,
                msg = msg
            };
            return result;
        }
        /// <summary>
        /// 把json字符串转成对象
        /// </summary>
        /// <typeparam name="T">对象</typeparam>
        /// <param name="data">json字符串</param> 
        public static T Deserialize<T>(string data)
        {
            return JsonConvert.DeserializeObject<T>(data);
        }

        /// <summary>
        /// 把对象转成json字符串
        /// </summary>
        /// <param name="o">对象</param>
        /// <returns>json字符串</returns>
        public static string Serialize(object o)
        {
            return JsonConvert.SerializeObject(o);
        }

        /// <summary>
        /// 把DataTable对象转成json字符串
        /// </summary> 
        public string ToJson(DataTable dt)
        {

            ArrayList arrayList = new ArrayList();
            foreach (DataRow dataRow in dt.Rows)
            {
                Dictionary<string, object> dictionary = new Dictionary<string, object>();
                foreach (DataColumn dataColumn in dt.Columns)
                {
                    dictionary.Add(dataColumn.ColumnName, dataRow[dataColumn.ColumnName]);
                }
                arrayList.Add(dictionary);
            }
            return JsonConvert.SerializeObject(arrayList);
        }
    }

    /// <summary>
    ///Result 的摘要说明
    /// </summary>
    public class Result
    {
        public Result()
        {
        }

        public bool isok
        {
            get; set;
        }

        public int code
        {
            get
            {
                if (isok) { return 0; }
                return -1;
            }
            set => throw new System.NotImplementedException();
        }

        public int count { get; set; }

        public string msg
        {
            get; set;
        }
        public object data
        {
            get; set;
        }

        public string ToJson()
        {
            return JsonConvert.SerializeObject(this);
        }
    }
}